package org.apache.skywalking.apm.plugin.spring.mvc.commons.interceptor;

import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class DispatcherServletInterceptor implements InstanceMethodsAroundInterceptor {

    @Override
    public void beforeMethod(EnhancedInstance obj, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
                             MethodInterceptResult result) {
        // 在方法执行前，可以进行一些初始化操作，这里暂时为空
        // 获取当前的Span
        String globalTraceId = ContextManager.getGlobalTraceId();
        if (StringUtil.isNotBlank(globalTraceId)) {
            // 获取HttpServletResponse对象，用于添加响应头
            HttpServletResponse response = (HttpServletResponse) allArguments[1];
            response.setHeader("traceId", globalTraceId);
        }
    }

    @Override
    public Object afterMethod(EnhancedInstance obj, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
                              Object ret) {
        return ret;
    }

    @Override
    public void handleMethodException(EnhancedInstance obj, Method method, Object[] allArguments,
                                      Class<?>[] argumentsTypes, Throwable t) {
    }
}